#include "comboboxdelegate.h"
#include "defs.h"
#include <QComboBox>

ComboBoxDelegate::ComboBoxDelegate(QObject *parent) :
    QStyledItemDelegate(parent),
    mItems (NULL)
{

}

ComboBoxDelegate::ComboBoxDelegate(const QStringList &items, QObject *parent) :
    QStyledItemDelegate(parent),
    mItems(NULL)
{
    mItems = new QStringList(items);
}

ComboBoxDelegate::~ComboBoxDelegate()
{
    if (mItems!=NULL)
        delete mItems;
}

QString ComboBoxDelegate::displayText(const QVariant &value, const QLocale &locale) const
{
    bool ok = false;
    int val = value.toInt(&ok);
    if (ok)
    {
        return mItems->at(val);
    } else {
        return QStyledItemDelegate::displayText(NOT_CORRECT, locale);
    }
}

QWidget *ComboBoxDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(index);
    QComboBox *edt = new QComboBox(parent);
    edt->setGeometry(option.rect);
    edt->addItems( *mItems );
    return edt;
}

void ComboBoxDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    QComboBox *edt  = qobject_cast<QComboBox *>(editor);
    model->setData(index, edt->currentIndex());
}

void ComboBoxDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QComboBox *edt  = qobject_cast<QComboBox *>(editor);
    const int currentIndex = index.data().toInt();
    edt->setCurrentIndex( currentIndex );
}
